package xin.petstore.framework.orm.mybatis.paginator.springmvc;

import xin.petstore.framework.orm.mybatis.paginator.domain.PageList;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import xin.petstore.framework.orm.mybatis.paginator.domain.Paginator;

public class PageListAttrHandlerInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse httpServletResponse, Object o)
            throws Exception {
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        Enumeration enumeration = request.getAttributeNames();
        PageList pageList;
        while (enumeration.hasMoreElements()) {
            Object element = enumeration.nextElement();
            if ((element instanceof String)) {
                String name = (String) element;
                Object attr = request.getAttribute(name);
                if ((attr instanceof PageList)) {
                    pageList = (PageList) attr;

                    request.setAttribute(name + "Paginator", pageList.getPaginator());
                }
            }
        }
        if (modelAndView != null) {
            Map<String, Object> model = modelAndView.getModel();
            Map<String, Object> newModel = new HashMap();
            for (Entry item : model.entrySet()) {
                Object attr = item.getValue();
                if ((attr instanceof PageList)) {
                    PageList pageList = (PageList) attr;
                    newModel.put((String) item.getKey() + "Paginator", pageList.getPaginator());
                }
            }
            modelAndView.addAllObjects(newModel);
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse httpServletResponse, Object o, Exception e)
            throws Exception {
    }
}

